package com.york.controller;

import com.york.entity.User;
import com.york.service.UserService;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author york.young
 * @description Export2Controller:
 * @date 2022/3/31
 */
@Controller
public class JxslCoreController {
    @Autowired
    private UserService userService;


    /**
     * @description 使用jxls-core包下的jxls语法来导出excel文件
     * @author york.young
     * http://localhost:8082/exportByJxls
     */
    @GetMapping("exportByJxlsCore")
    public void export(HttpServletResponse response) {
        try (InputStream is = JxslCoreController.class.getClassLoader().getResourceAsStream("template/用户列表.xlsx");
             OutputStream os = response.getOutputStream()) {
            List<User> list = userService.selectList();
            // 表格使用的数据
            Map<String, Object> excelMap = new HashMap<>(1);
            excelMap.put("data", list);
            // 实例化 XLSTransformer 对象
            XLSTransformer xlsTransformer = new XLSTransformer();
            // 获取 Workbook ，传入 模板 和 数据
            // 获取模板文件
            String fileName = "用户列表.xlsx";
            Workbook workbook = xlsTransformer.transformXLS(is, excelMap);
            fileName = new String(fileName.getBytes(), "ISO8859-1");
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            workbook.write(os);
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
